package ${package}.config.oauth;

import ${package}.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 服务端异常，用户名密码错误，无效的认证方式
 *
 * @author ${author}
 * @date ${date}
 */
@Component
public class CustomWebResponseExceptionHandler implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity<Result<String>> translate(Exception e) {
        Result<String> response = resolveException(e);
        return new ResponseEntity<>(response, HttpStatus.valueOf(response.getCode()));
    }

    /**
     * 构建返回异常
     *
     * @param e exception
     * @return
     */
    private Result<String> resolveException(Exception e) {
        if (e instanceof InvalidGrantException) {
            Result<String> failResponse = Result.error("用户名或密码错误！");
            failResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return failResponse;
        }
        if (e instanceof InvalidScopeException
                || e instanceof InvalidClientException
                || e instanceof UnsupportedGrantTypeException
                || e instanceof InvalidRequestException
        ) {
            Result<String> failResponse = Result.error("无效的认证方式！");
            failResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return failResponse;
        }
        return Result.error(e.getMessage());
    }
}
